<!DOCTYPE html>

<html lang="en">
  <head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>使用控制器（Using Controllers） &mdash; Phalcon 3.0.1 文档</title>
    <meta name="keywords" content="php, phalcon, phalcon php, php framework, faster php framework">
    <link rel="stylesheet" type="text/css" href="http://cdn.staticfile.org/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="/www/css/phalcon.min.css" />
    <link href='//fonts.googleapis.com/css?family=Open+Sans:700,400' rel='stylesheet' type='text/css'>
    <link href="//fonts.googleapis.com/css?family=Merriweather:400,700" rel="stylesheet" type="text/css" />
    <!--
    EUROPE <link href='//fonts.googleapis.com/css?family=Open+Sans:700,400&subset=latin-ext' rel='stylesheet' type='text/css'>
    GREEK <link href='//fonts.googleapis.com/css?family=Open+Sans:700,400&subset=greek-ext' rel='stylesheet' type='text/css'>
    RUSSIA <link href='//fonts.googleapis.com/css?family=Open+Sans:700,400&subset=cyrillic-ext,latin' rel='stylesheet' type='text/css'>
    -->

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <link rel="stylesheet" href="../static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../static/docs.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.0.1',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>

    <script src="http://cdn.staticfile.org/jquery/1.8.1/jquery.min.js"></script>
    <script type="text/javascript" src="../static/docs.js"></script>
    <link rel="shortcut icon" href="../static/favicon.ico"/>
    <link rel="top" title="Phalcon 3.0.1 文档" href="../index.html" />
    <link rel="next" title="使用模型（Working with Models）" href="models.html" />
    <link rel="prev" title="MVC 架构（The MVC Architecture）" href="mvc.html" /> 
  </head>
  <body>

<header class="page-header">
    <nav class="navbar" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-menu-container">
                    <span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
                </button>
                <a class="navbar-brand phalcon-logo" href="/"><span itemprop="name" class="sr-only">Phalcon PHP</span></a>
            </div>

            <div class="collapse navbar-collapse navbar-right" id="main-menu-container">
                <ul class="nav navbar-nav main-menu">
                  <li class="first"><a href="//phalconphp.com/en/download" class="header-nav-link">Download</a></li>
                  <li><a href="//docs.phalconphp.com/en/latest/index.html" class="header-nav-link" target="_blank">Documentation</a></li>
                  <li><a href="//forum.phalconphp.com/" class="header-nav-link" target="_blank">Forum</a></li>
                  <li><a href="//blog.phalconphp.com/" class="header-nav-link" target="_blank">Blog</a></li>
                  <li><a href="//phalconist.com/" class="header-nav-link" target="_blank">Resources</a></li>
                  <li><a href="//phalconphp.com/en/about">About</a></li>
                  <li><div align="right">
                      <iframe src="https://ghbtns.com/github-btn.html?user=phalcon&amp;repo=cphalcon&amp;type=watch&amp;count=true&amp;size=large"
      allowtransparency="true" frameborder="0" scrolling="0" width="152px" height="30px"></iframe>
                    </div></li>
                </ul>
            </div>
        </div>
    </nav>
  </header>

<div class="heading">
    <div class="container">
        <div class="row">
            <h2>Documentation</h2>
        </div>
    </div>
</div>
    <div class="related">
      <ul>
        <li class="right" >
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="models.html" title="使用模型（Working with Models）"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="mvc.html" title="MVC 架构（The MVC Architecture）"
             accesskey="P">上一页</a> |</li>
        <li><a href="//phalconphp.com">Home</a> &raquo;</li>
        <li><a href="../index.html">Phalcon 3.0.1 文档</a> &raquo;</li> 
      </ul>
    </div>  

      <table width="100%" align="center" cellpadding="0" cellspacing="0">
        <tr>
      <td class="primary-box" width="25%" valign="top">
            <div>
            <div id="searchbox" style="">
                <!--<form class="search" action="http://readthedocs.org/search/project/" method="get">
                  <input type="search" name="q" size="25" placeholder="Search">
                  <input type="submit" value="Go">
                  <input type="hidden" name="selected_facets" value="project:">
                </form>-->
                <div style="width:200px;padding:10px">
                  <gcse:searchbox-only></gcse:searchbox-only>
                </div>
            </div>
            </div>
            <div style="padding:5px;padding-left:10px">
              <div id="carbonads-container">
                <div class="carbonad"><div id="azcarbon"></div>
                <script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=phalconphpcom" id="_carbonads_js"></script>
                </div></div>
            </div>
            <h3><a href="../index.html">內容目录</a></h3>
            <ul>
<li><a class="reference internal" href="#">使用控制器（Using Controllers）</a><ul>
<li><a class="reference internal" href="#dispatch-loop">循环调度（Dispatch Loop）</a></li>
<li><a class="reference internal" href="#initializing-controllers">初始化控制器（Initializing Controllers）</a></li>
<li><a class="reference internal" href="#injecting-services">注入服务（Injecting Services）</a></li>
<li><a class="reference internal" href="#request-and-response">请求与响应（Request and Response）</a></li>
<li><a class="reference internal" href="#session-data">会话数据（Session Data）</a></li>
<li><a class="reference internal" href="#using-services-as-controllers">在控制器中使用服务（Using Services as Controllers）</a></li>
<li><a class="reference internal" href="#creating-a-base-controller">创建基类控制器（Creating a Base Controller）</a></li>
<li><a class="reference internal" href="#events-in-controllers">控制器中的事件（Events in Controllers）</a></li>
</ul>
</li>
</ul>

            <h4>上一个主题</h4>
            <p class="topless"><a href="mvc.html" title="上一章">&lt; MVC 架构（The MVC Architecture）</a></p>
            <h4>下一个主题</h4>
            <p class="topless"><a href="models.html" title="下一章">使用模型（Working with Models） &gt;</a></p>
            <h3>本页</h3>
            <ul class="this-page-menu">
              <li><a href="../sources/reference/controllers.md" rel="nofollow">显示源代码</a></li>
            </ul>
        </td>
          <td class="second-box" valign="top">
            <div class="document">
                <div class="documentwrapper">
                  <div class="bodywrapper">
                    <div class="body" >
                      
  <div class="section" id="using-controllers">
<h1>使用控制器（Using Controllers）<a class="headerlink" href="#using-controllers" title="永久链接至标题">¶</a></h1>
<p>控制器提供了一堆可以被调用的方法，即：action。action是控制器中用于处理请求的方法。默认情况下，全部
控制器public的方法都会映射到action并且可以通过URL访问。action负责解释请求和创建响应。
通常，响应是以渲染的视图格式被创建，但也存在其他的方式来创建（译者注：如AJAX请求返回JSON格式的数据）。</p>
<p>例如，当你访问一个类似这样的URL时：<a class="reference external" href="http://localhost/blog/posts/show/2015/the-post-title">http://localhost/blog/posts/show/2015/the-post-title</a>，Phalcon默认会这样分解各个部分：</p>
<table border="1" class="docutils">
<colgroup>
<col width="52%" />
<col width="48%" />
</colgroup>
<tbody valign="top">
<tr class="row-odd"><td><strong>Phalcon目录</strong></td>
<td>blog</td>
</tr>
<tr class="row-even"><td><strong>控制器</strong></td>
<td>posts</td>
</tr>
<tr class="row-odd"><td><strong>Action</strong></td>
<td>show</td>
</tr>
<tr class="row-even"><td><strong>参数</strong></td>
<td>2015</td>
</tr>
<tr class="row-odd"><td><strong>参数</strong></td>
<td>the-post-title</td>
</tr>
</tbody>
</table>
<p>这时，PostsController将会处理这个请求。在一个项目中，没有强制指定放置控制器的地方，这些控制器都可以
通过使用 <a class="reference internal" href="loader.html"><em>autoloaders</em></a> 来加载，所以你可以根据需要自由组件你的控制器。</p>
<p>控制器类必须以“Controller”为后缀，action则须以“Action”为后缀。一个控制器类的例子如下：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">indexAction</span><span class="p">()</span>
    <span class="p">{</span>

    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">showAction</span><span class="p">(</span><span class="nv">$year</span><span class="p">,</span> <span class="nv">$postTitle</span><span class="p">)</span>
    <span class="p">{</span>

    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>额外的URI参数定义为action的参数，以致这些参数可以简单地通过本地变量来获取。控制器
可以选择继承 <a class="reference internal" href="../api/Phalcon_Mvc_Controller.html"><em>Phalcon\Mvc\Controller</em></a> 。如果继承此基类，你的控制器类则能
轻松访问应用的各种服务。</p>
<p>没有默认缺省值的参数视为必须参数处理。可以像PHP那样为参数设定一个默认值：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">indexAction</span><span class="p">()</span>
    <span class="p">{</span>

    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">showAction</span><span class="p">(</span><span class="nv">$year</span> <span class="o">=</span> <span class="mi">2015</span><span class="p">,</span> <span class="nv">$postTitle</span> <span class="o">=</span> <span class="s2">&quot;some default title&quot;</span><span class="p">)</span>
    <span class="p">{</span>

    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>参数将会按路由传递和函数定义一样的顺序来赋值。你可以使用以下根据参数名称的方式来获取任意一个参数：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">indexAction</span><span class="p">()</span>
    <span class="p">{</span>

    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">showAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$year</span>      <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">dispatcher</span><span class="o">-&gt;</span><span class="na">getParam</span><span class="p">(</span><span class="s2">&quot;year&quot;</span><span class="p">);</span>
        <span class="nv">$postTitle</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">dispatcher</span><span class="o">-&gt;</span><span class="na">getParam</span><span class="p">(</span><span class="s2">&quot;postTitle&quot;</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="section" id="dispatch-loop">
<h2>循环调度（Dispatch Loop）<a class="headerlink" href="#dispatch-loop" title="永久链接至标题">¶</a></h2>
<p>循环调度将会在分发器执行，直到没有action需要执行为止。在上面的例子中，只有一个action
被执行到。现在让我们来看下:code:<a href="#id1"><span class="problematic" id="id2">`</span></a>forward()`（转发）怎样才能在循环调度里提供一个更加复杂的操作流，从而将执行转发到
另一个controller/action。</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">indexAction</span><span class="p">()</span>
    <span class="p">{</span>

    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">showAction</span><span class="p">(</span><span class="nv">$year</span><span class="p">,</span> <span class="nv">$postTitle</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">flash</span><span class="o">-&gt;</span><span class="na">error</span><span class="p">(</span>
            <span class="s2">&quot;You don&#39;t have permission to access this area&quot;</span>
        <span class="p">);</span>

        <span class="c1">// Forward flow to another action</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">dispatcher</span><span class="o">-&gt;</span><span class="na">forward</span><span class="p">(</span>
            <span class="p">[</span>
                <span class="s2">&quot;controller&quot;</span> <span class="o">=&gt;</span> <span class="s2">&quot;users&quot;</span><span class="p">,</span>
                <span class="s2">&quot;action&quot;</span>     <span class="o">=&gt;</span> <span class="s2">&quot;signin&quot;</span><span class="p">,</span>
            <span class="p">]</span>
        <span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>如果用户没有访问某个action的权限，那么请求将会被转发到Users控制器的signin行为。</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">UsersController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">indexAction</span><span class="p">()</span>
    <span class="p">{</span>

    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">signinAction</span><span class="p">()</span>
    <span class="p">{</span>

    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>对于“forwards”转发的次数没有限制，只要不会形成循环重定向即可，否则就意味着
你的应用将会停止（译者注：如果浏览器发现一个请求循环重定向时，会终止请求）。
如果在循环调度里面没有其他action可以分发，分发器将会自动调用由 <a class="reference internal" href="../api/Phalcon_Mvc_View.html"><em>Phalcon\Mvc\View</em></a> 管理的MVC的视图层。</p>
</div>
<div class="section" id="initializing-controllers">
<h2>初始化控制器（Initializing Controllers）<a class="headerlink" href="#initializing-controllers" title="永久链接至标题">¶</a></h2>
<p><a class="reference internal" href="../api/Phalcon_Mvc_Controller.html"><em>Phalcon\Mvc\Controller</em></a> 提供了初始化的函数，它会最先执行，并优于任何控制器
的其他action。不推荐使用“__construct&#8221;方法。</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="nv">$settings</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">initialize</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">settings</span> <span class="o">=</span> <span class="p">[</span>
            <span class="s2">&quot;mySetting&quot;</span> <span class="o">=&gt;</span> <span class="s2">&quot;value&quot;</span><span class="p">,</span>
        <span class="p">];</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">saveAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">settings</span><span class="p">[</span><span class="s2">&quot;mySetting&quot;</span><span class="p">]</span> <span class="o">===</span> <span class="s2">&quot;value&quot;</span><span class="p">)</span> <span class="p">{</span>
            <span class="c1">// ...</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<blockquote class="highlights">
<div>:code:<a href="#id3"><span class="problematic" id="id4">`</span></a>initialize()`仅仅会在事件“beforeExecuteRoute”成功执行后才会被调用。这样可以避免
在初始化中的应用逻辑在未鉴权的情况下无法执行。</div></blockquote>
<p>如果你想在紧接着创建控制器对象的后面执行一些初始化的逻辑，你要实现:code:<cite>onConstruct()</cite>”方法：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">onConstruct</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="c1">// ...</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<blockquote class="highlights">
<div>需要注意的是，即使待执行的action在控制器不存在，或者用户没有
访问到它（根据开发人员提供的自定义控制器接入），“onConstruct”都会被执行。</div></blockquote>
</div>
<div class="section" id="injecting-services">
<h2>注入服务（Injecting Services）<a class="headerlink" href="#injecting-services" title="永久链接至标题">¶</a></h2>
<p>如果控制器继承于 <a class="reference internal" href="../api/Phalcon_Mvc_Controller.html"><em>Phalcon\Mvc\Controller</em></a> ，那么它可以轻松访问
应用的服务容器。例如，如果我们类似这样注册了一个服务：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Di</span><span class="p">;</span>

<span class="nv">$di</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Di</span><span class="p">();</span>

<span class="nv">$di</span><span class="o">-&gt;</span><span class="na">set</span><span class="p">(</span>
    <span class="s2">&quot;storage&quot;</span><span class="p">,</span>
    <span class="k">function</span> <span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="k">new</span> <span class="nx">Storage</span><span class="p">(</span>
            <span class="s2">&quot;/some/directory&quot;</span>
        <span class="p">);</span>
    <span class="p">},</span>
    <span class="k">true</span>
<span class="p">);</span>
</pre></div>
</div>
<p>那么，我们可以通常多种方式来访问这个服务：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">FilesController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">saveAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="c1">// 以和服务相同名字的类属性访问</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">storage</span><span class="o">-&gt;</span><span class="na">save</span><span class="p">(</span><span class="s2">&quot;/some/file&quot;</span><span class="p">);</span>

        <span class="c1">// 通过DI访问服务</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">di</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s2">&quot;storage&quot;</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">save</span><span class="p">(</span><span class="s2">&quot;/some/file&quot;</span><span class="p">);</span>

        <span class="c1">// 另一种方式：使用魔法getter来访问</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">di</span><span class="o">-&gt;</span><span class="na">getStorage</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">save</span><span class="p">(</span><span class="s2">&quot;/some/file&quot;</span><span class="p">);</span>

        <span class="c1">// 另一种方式：使用魔法getter来访问</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getDi</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">getStorage</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">save</span><span class="p">(</span><span class="s2">&quot;/some/file&quot;</span><span class="p">);</span>

        <span class="c1">// 使用数组下标</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">di</span><span class="p">[</span><span class="s2">&quot;storage&quot;</span><span class="p">]</span><span class="o">-&gt;</span><span class="na">save</span><span class="p">(</span><span class="s2">&quot;/some/file&quot;</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>如果你是把Phalcon作为全能(Full-Stack)框架来使用，你可以阅读框架中 <a class="reference internal" href="di.html"><em>by default</em></a> 提供的服务。</p>
</div>
<div class="section" id="request-and-response">
<h2>请求与响应（Request and Response）<a class="headerlink" href="#request-and-response" title="永久链接至标题">¶</a></h2>
<p>假设框架预先提供了一系列的注册的服务。我们这里将解释如何和HTTP环境进行关联和交互。
“request”服务包含了一个 <a class="reference internal" href="../api/Phalcon_Http_Request.html"><em>Phalcon\Http\Request</em></a> 的实例，
“response”服务则包含了一个 <a class="reference internal" href="../api/Phalcon_Http_Response.html"><em>Phalcon\Http\Response</em></a> 的实例，用来表示将要返回给客户端的内容。</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">indexAction</span><span class="p">()</span>
    <span class="p">{</span>

    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">saveAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="c1">// 检查请求是否为POST</span>
        <span class="k">if</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">isPost</span><span class="p">())</span> <span class="p">{</span>
            <span class="c1">// 获取POST数据</span>
            <span class="nv">$customerName</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">getPost</span><span class="p">(</span><span class="s2">&quot;name&quot;</span><span class="p">);</span>
            <span class="nv">$customerBorn</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">getPost</span><span class="p">(</span><span class="s2">&quot;born&quot;</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>响应对象通常不会直接使用，但在action的执行前会被创建，有时候 - 如在
一个afterDispatch事件中 - 它对于直接访问响应非常有帮助：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">indexAction</span><span class="p">()</span>
    <span class="p">{</span>

    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">notFoundAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="c1">// 发送一个HTTP 404 响应的header</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">response</span><span class="o">-&gt;</span><span class="na">setStatusCode</span><span class="p">(</span><span class="mi">404</span><span class="p">,</span> <span class="s2">&quot;Not Found&quot;</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>如需学习了解HTTP环境更多内容，请查看专题： <a class="reference internal" href="request.html"><em>request</em></a> 和 <a class="reference internal" href="response.html"><em>response</em></a> 。</p>
</div>
<div class="section" id="session-data">
<h2>会话数据（Session Data）<a class="headerlink" href="#session-data" title="永久链接至标题">¶</a></h2>
<p>会话可以帮助我们在多个请求中保持持久化的数据。你可以从任何控制器中访问 <a class="reference internal" href="../api/Phalcon_Session_Bag.html"><em>Phalcon\Session\Bag</em></a>
以便封装需要进行持久化的数据。</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">UserController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">indexAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">persistent</span><span class="o">-&gt;</span><span class="na">name</span> <span class="o">=</span> <span class="s2">&quot;Michael&quot;</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">welcomeAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">echo</span> <span class="s2">&quot;Welcome, &quot;</span><span class="p">,</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">persistent</span><span class="o">-&gt;</span><span class="na">name</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="using-services-as-controllers">
<h2>在控制器中使用服务（Using Services as Controllers）<a class="headerlink" href="#using-services-as-controllers" title="永久链接至标题">¶</a></h2>
<p>服务可以是控制器，控制器类通常会从服务容器中请求。据于此，
任何一个用其名字注册的类都可以轻易地用一个控制器来替换：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="c1">// 将一个控制器作为服务进行注册</span>
<span class="nv">$di</span><span class="o">-&gt;</span><span class="na">set</span><span class="p">(</span>
    <span class="s2">&quot;IndexController&quot;</span><span class="p">,</span>
    <span class="k">function</span> <span class="p">()</span> <span class="p">{</span>
        <span class="nv">$component</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Component</span><span class="p">();</span>

        <span class="k">return</span> <span class="nv">$component</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">);</span>

<span class="c1">// 将一个命名空间下的控制器作为服务进行注册</span>
<span class="nv">$di</span><span class="o">-&gt;</span><span class="na">set</span><span class="p">(</span>
    <span class="s2">&quot;Backend</span><span class="se">\\</span><span class="s2">Controllers</span><span class="se">\\</span><span class="s2">IndexController&quot;</span><span class="p">,</span>
    <span class="k">function</span> <span class="p">()</span> <span class="p">{</span>
        <span class="nv">$component</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Component</span><span class="p">();</span>

        <span class="k">return</span> <span class="nv">$component</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">);</span>
</pre></div>
</div>
</div>
<div class="section" id="creating-a-base-controller">
<h2>创建基类控制器（Creating a Base Controller）<a class="headerlink" href="#creating-a-base-controller" title="永久链接至标题">¶</a></h2>
<p>对于某些应用特性如访问控制列表（ACL），翻译，缓存，和模板引擎一般对于
控制器都是通用的。在这种情况下，我们鼓励创建一个 “基类控制器”，从而确保你的代码遵循 <a class="reference external" href="https://zh.wikipedia.org/wiki/%E4%B8%80%E6%AC%A1%E4%B8%94%E4%BB%85%E4%B8%80%E6%AC%A1">DRY</a> 编程原则。
基类控制器可以是一个简单的类，然后继承于 <a class="reference internal" href="../api/Phalcon_Mvc_Controller.html"><em>Phalcon\Mvc\Controller</em></a> ，并封装
全部控制器都有的通用功能操作。反过来，你的控制器则继承这个“基类控制器”以便可以直接使用通用功能操作。</p>
<p>这个基类可以放置在任何一个地方，但出于代码组织的便利我们推荐应该放置在控制器的目录下，
如：apps/controllers/ControllerBase.php。我们可以在启动文件直接require这个文件，也可以使用自动加载：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">require</span> <span class="s2">&quot;../app/controllers/ControllerBase.php&quot;</span><span class="p">;</span>
</pre></div>
</div>
<p>对通用组件（action，方法，和类属性等）也在这个基类文件里面：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">ControllerBase</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="sd">/**</span>
<span class="sd">     * 这个方法可以被不同的控制器子类使用</span>
<span class="sd">     */</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">someAction</span><span class="p">()</span>
    <span class="p">{</span>

    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>现在，其他全部的控制都继承于ControllerBase，然后便可访问通用组件（如上面讲到的的）：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">class</span> <span class="nc">UsersController</span> <span class="k">extends</span> <span class="nx">ControllerBase</span>
<span class="p">{</span>

<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="events-in-controllers">
<h2>控制器中的事件（Events in Controllers）<a class="headerlink" href="#events-in-controllers" title="永久链接至标题">¶</a></h2>
<p>控制器会自动作为 <a class="reference internal" href="dispatching.html"><em>dispatcher</em></a> 事件的侦听者，使用这些事件并实现这些方法后，
你便可以实现对应被执行的action的before/after钩子函数：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">beforeExecuteRoute</span><span class="p">(</span><span class="nv">$dispatcher</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// 这个方法会在每一个能找到的action前执行</span>
        <span class="k">if</span> <span class="p">(</span><span class="nv">$dispatcher</span><span class="o">-&gt;</span><span class="na">getActionName</span><span class="p">()</span> <span class="o">===</span> <span class="s2">&quot;save&quot;</span><span class="p">)</span> <span class="p">{</span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">flash</span><span class="o">-&gt;</span><span class="na">error</span><span class="p">(</span>
                <span class="s2">&quot;You don&#39;t have permission to save posts&quot;</span>
            <span class="p">);</span>

            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">dispatcher</span><span class="o">-&gt;</span><span class="na">forward</span><span class="p">(</span>
                <span class="p">[</span>
                    <span class="s2">&quot;controller&quot;</span> <span class="o">=&gt;</span> <span class="s2">&quot;home&quot;</span><span class="p">,</span>
                    <span class="s2">&quot;action&quot;</span>     <span class="o">=&gt;</span> <span class="s2">&quot;index&quot;</span><span class="p">,</span>
                <span class="p">]</span>
            <span class="p">);</span>

            <span class="k">return</span> <span class="k">false</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">afterExecuteRoute</span><span class="p">(</span><span class="nv">$dispatcher</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// 在找到的action后执行</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
</div>


                    </div>
                  </div>
                </div>
            </div>
          </td>
        </tr>
      </table>
    <div class="related">
      <ul>
        <li class="right" >
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="models.html" title="使用模型（Working with Models）"
             >下一页</a> |</li>
        <li class="right" >
          <a href="mvc.html" title="MVC 架构（The MVC Architecture）"
             >上一页</a> |</li> 
      </ul>
    </div>

      <div class="prefooter">
  <div class="container">
      <div class="row">
          <div class="col-sm-3 text-right">
              <span>Follow along:</span>
          </div>
          <div class="col-sm-6 text-center">
              <a href="https://twitter.com/phalconphp" alt="Twitter" class="btn-social btn-social-twitter"><i class="icon-twitter"></i></a>
              <a href="https://www.facebook.com/pages/Phalcon-Framework/134230726685897" alt="Facebook" class="btn-social btn-social-facebook"><i class="icon-facebook"></i></a>
              <a href="https://plus.google.com/102376109340560896457" alt="Google+" class="btn-social btn-social-googleplus"><i class="icon-googleplus"></i></a>
              <a href="https://github.com/phalcon/cphalcon" alt="Github" class="btn-social btn-social-github"><i class="icon-github"></i></a>
          </div>
          <div class="col-sm-3">
          </div>
      </div>
  </div>

</div>
<footer class="footer">
    <div class="container">
        <div class="row">
            <div class="col-xs-4 col-sm-3">
                <h4>Download</h4>
                <ul>
                    <li><a href="/download">Installing Phalcon PHP</a></li>
                    <li><a href="http://docs.phalconphp.com/en/latest/index.html" class="header-nav-link" target="_blank">Documentation</a></li>
                    <li><a href="http://api.phalconphp.com">API</a></li>
                    <li><a href="http://docs.phalconphp.com/en/latest/reference/tutorial.html">Tutorial</a></li>
                    <li><a href="http://docs.phalconphp.com/en/latest/reference/tutorial.html#sample-applications">Sample Applications</a></li>
                </ul>
            </div>
            <div class="col-xs-4 col-sm-3">
                <h4>Community</h4>
                <ul>
                    <li><a href="http://forum.phalconphp.com/" class="header-nav-link" target="_blank">Forum</a></li>
                    <li><a href="https://github.com/phalcon/cphalcon">GitHub</a></li>
                    <li><a href="https://github.com/phalcon/cphalcon/issues">Issue Tracker</a></li>
                    <li><a href="http://stackoverflow.com/questions/tagged/phalcon">Stack Overflow</a></li>
                    <li><a href="/en/testimonials">Testimonials</a></li>
                    <li><a href="http://builtwith.phalconphp.com/">Built with Phalcon</a></li>
                    <li><a href="http://store.phalconphp.com/">Store</a></li>
                </ul>
            </div>
            <div class="col-xs-4 col-sm-2">
                <h4>About</h4>
                <ul>
                    <li><a class="link-black" href="http://blog.phalconphp.com/">Blog</a></li>
                    <li><a href="/en/about">About</a></li>
                    <li><a href="/en/team">Team</a></li>
                    <li><a href="/en/roadmap">Roadmap</a></li>
                    <li><a href="/en/donate">Donate</a></li>
                    <li><a href="/en/consulting">Consulting</a></li>
                    <li><a href="/en/hosting">Hosting</a></li>
                </ul>
            </div>
            <div id="license-spaccer" class="visible-xs"></div>
            <div id="license-wrapper" class="col-xs-12 col-sm-4">
                <p class="license">
                    Phalcon is an open-source PHP framework <br>built as a C-extension. It is available under the <br>
                    <a href="http://opensource.org/licenses/BSD-3-Clause" target="_blank">new BSD License</a>.
                    <br>
                    <br>
                    Except where otherwise noted, content on this site is licensed under the
                    <a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 License.</a>
                </p>
            </div>
        </div>
    </div>
</footer>

    </div>
    <script type="text/javascript">
    $(window).on("load", function(){
      var cx = '009733439235723428699:lh9ltjgvdz8';
      var gcse = document.createElement('script');
      gcse.type = 'text/javascript';
      gcse.async = true;
      gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx;
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(gcse, s);
    });
    </script>

  </body>
</html>